<?php

namespace app\admin\controller;

use app\admin\logic\Form3Logic;
use app\admin\model\Form7;
use app\admin\model\TemperatureAlarm;
use app\admin\model\Town;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\App;
use think\Exception;
use think\facade\Db;
use app\admin\model\Community;

/**
 * @ControllerAnnotation(title="购药人员信息管理")
 */
class Form3 extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Form3();

        $this->assign('getCommunityList', Community::getCommunityList());
        $this->assign('getTownList', Town::getTownList());
        $this->assign('getTownList2', Town::getTownList2());

    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();

            if (!$this->isSuper) {
                $where[] = ['community', '=', $this->user->community_id];
            }

            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'drug_name|药品名称'                 =>  'require',
                'name|购药人姓名'                    =>  'require|chs',
                'sex|性别'                           =>  'require',
                'pharmacy|购药药店'                  =>  'require',
                'is_fever|是否有退烧功能'            =>  'require',
                'id_card|身份证号'                   =>  'require|idCard',
                'living|居住地址'                    =>  'require',
                'buy_time|购药时间'                  =>  'require|date',
                'mobile|手机号码'                    =>  'require|mobile',
            ];
            $this->validate($post, $rule);

            if (strtotime($post['buy_time']) > time()) {
                $this->error('购药时间不能大于当前');
            }

            if ($this->model->whereDay('create_time')->where('id_card', $post['id_card'])->count() > 0) {
                $this->error('该身份证号今日已经录入了');
            }

            if (!$this->isSuper) {
                $post['town'] = 1;
                $post['community'] = $this->user->community_id;
            } else {
                empty($post['town']) && $this->error('居住地所属乡镇不能为空');
                !isset($post['community']) && $this->error('居住地所属社区不能为空');
            }

            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $row = $this->model->find($this->request->param($this->model->getPk()));
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'drug_name|药品名称'                 =>  'require',
                'name|购药人姓名'                    =>  'require|chs',
                'sex|性别'                           =>  'require',
                'pharmacy|购药药店'                  =>  'require',
                'is_fever|是否有退烧功能'            =>  'require',
                'id_card|身份证号'                   =>  'require|idCard',
                'living|居住地址'                    =>  'require',
                'buy_time|购药时间'                  =>  'require|date',
                'mobile|手机号码'                    =>  'require|mobile',
            ];
            $this->validate($post, $rule);

            if (strtotime($post['buy_time']) > time()) {
                $this->error('购药时间不能大于当前');
            }

            if (!$this->isSuper) {
                $post['town'] = 1;
                $post['community'] = $this->user->community_id;
            } else {
                empty($post['town']) && $this->error('居住地所属乡镇不能为空');
                !isset($post['community']) && $this->error('居住地所属社区不能为空');
            }

            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete()
    {
        $row = $this->model->whereIn($this->model->getPk(), $this->request->param($this->model->getPk()))->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix = config('database.connections.mysql.prefix');
        $dbList = Db::query("show full columns from {$prefix}{$tableName}");
        $header = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], $this->noExportFields)) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list = $this->model
            ->where($where)
            ->limit(100000)
            ->order($this->sort)
            ->select()
            ->toArray();
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="体温记录")
     */
    public function temperature_index()
    {
        return $this->temperature_index_common('form3');
    }

    /**
     * @NodeAnotation(title="添加体温记录")
     */
    public function temperature_add()
    {
        return $this->temperature_add_common();
    }

    /**
     * @NodeAnotation(title="导入")
     * @return mixed
     */
    public function import()
    {
        if ($this->request->isAjax()) {
            $post = [
                'upload_type' => 'local',
                'file'        => $this->request->file('file'),
            ];

            $uploadConfig = sysconfig('upload');
            $rule = [
                'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
                'file|文件'                    => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
            ];
            $this->validate($post, $rule);

            $result = Form3Logic::import($post);
            if ($result === false){
                $this->error(self::getError());
            }
            $this->success('导入成功');
        }
        $this->assign('download_url', url('ajax/download_templet', ['name' => '购药人员信息导入表.xlsx']));
        return $this->fetch('common/import');
    }
    
}